import json
import time
from datetime import datetime
import pytz

class SensorDataPoint:
    """传感器数据点类"""
    def __init__(self, data, timestamp=None):
        self.data = data
        self.timestamp = timestamp or time.time()
    
    def to_dict(self):
        return {
            'data': self.data,
            'timestamp': self.timestamp,
            'formatted_time': self.get_formatted_time()
        }
    
    def get_formatted_time(self):
        """获取格式化的时间字符串"""
        dt = datetime.fromtimestamp(self.timestamp, pytz.timezone('Asia/Shanghai'))
        return dt.strftime('%Y-%m-%d %H:%M:%S')

class SensorDataHistory:
    """传感器数据历史记录类"""
    def __init__(self, max_points=100):
        self.max_points = max_points
        self.data_points = []
    
    def add_data_point(self, data):
        """添加数据点"""
        data_point = SensorDataPoint(data)
        self.data_points.append(data_point)
        
        # 保持数据点数量不超过最大值
        if len(self.data_points) > self.max_points:
            self.data_points = self.data_points[-self.max_points:]
    
    def get_history(self, count=None):
        """获取历史数据"""
        count = count or self.max_points
        return [point.to_dict() for point in self.data_points[-count:]]
    
    def get_history_for_chart(self, key, count=None):
        """获取特定键的历史数据，用于图表显示"""
        count = count or self.max_points
        history = self.get_history(count)
        
        labels = [point['formatted_time'] for point in history]
        values = [point['data'].get(key, 0) for point in history]
        
        return {
            'labels': labels,
            'values': values
        }

# 创建传感器数据历史记录实例
sensor_history = SensorDataHistory()